package com.abel.bigwater.dataserver.model.qdies

import com.abel.bigwater.data.BcdString
import com.abel.bigwater.dataserver.model.PacketCmdException
import io.netty.buffer.ByteBuf

open class DtenAskPulseConfigData(_len: Int) : D10BaseData(_len) {
    override var type = FuncType.AskPulseConfig

    var internalAddr: Byte? = null

    var readMode = ReadModeType.DayMode

    /**
     * 上传时刻 2字节 两个字节分别代表星期， 小时
    的BCD码
     */
    var uploadStart: BcdString? = null

    var samplePeriod: Int? = null

    var uploadPeriod: Short? = null

    override fun fill(buf: ByteBuf) {
        assert(internalAddr != null && uploadStart?.size == 2 && samplePeriod != null && uploadPeriod != null)
        buf.apply {
            writeByte(internalAddr!!.toInt())
            writeByte(readMode.code.toInt())
            writeBytes(uploadStart!!.hexArray)
            writeShort(samplePeriod!!)
            writeByte(uploadPeriod!!.toInt())
        }
    }

    override fun parse(buf: ByteBuf): Boolean {
        buf.apply {
            internalAddr = readByte()
            val r1 = readByte()
            if (ReadModeType.values().find { it.code == r1 } == null) {
                throw PacketCmdException("invalid read-mode: $r1")
            }
            readMode = ReadModeType.values().find { it.code == r1 }!!

            uploadStart = BcdString.create(this, 2)
            samplePeriod = readUnsignedShort()
            uploadPeriod = readUnsignedByte()

        }

        return true
    }

    override fun count(): Int = 1 + 1 + 2 + 2 + 1
}